import {
  getSpotNextDate,
  fetchSessionList,
} from "../../../api/fishing-session";
import { formatDate } from "../../../utils/date";

Page({
  data: {
    pageLoading: false,
    startDate: "",
    endDate: "",
    deposit: "",
    listLoadStatus: 0,
    sessionList: [],
  },
  onLoad() {
    console.log("===onLoad=====");
    this.loadSessionList();
  },
  onReachBottom() {
    console.log("------onReachBottom---------");
    if (this.data.listLoadStatus === 0) {
      this.loadGoodsList();
    }
  },

  onPullDownRefresh() {
    console.log("------onPullDownRefresh---------");
    this.loadHomePage();
  },

  async loadGoodsList(fresh = false) {
    if (fresh) {
      wx.pageScrollTo({
        scrollTop: 0,
      });
    }
    this.setData({ listLoadStatus: 1 });
    setTimeout(() => {
      this.setData({ listLoadStatus: 2 });
    }, 3000);
  },

  loadHomePage() {
    wx.stopPullDownRefresh();
    this.setData({
      pageLoading: true,
    });
    setTimeout(() => {
      this.setData({
        pageLoading: false,
      });
    }, 3000);
    // fetchHome().then(({ swiper, tabList }) => {
    //   this.setData({
    //     tabList,
    //     imgSrcs: swiper,
    //     pageLoading: false,
    //   });
    //   this.loadGoodsList(true);
    // });
  },

  async loadSessionList(date, dir) {
    const spotId = getApp().globalData.spotId;
    const data = await fetchSessionList(spotId, date, dir);
    console.log("====loadSessionList====", data);
    if (data === null) {
      wx.showToast({
        title: "获取数据失败",
        icon: "none",
      });
      return;
    }
    this.setData({
      sessionList: data.items.map(this.formatItem),
    });
  },
  // 格式化返回
  formatItem(item) {
    const {
      id,
      date,
      timerange,
      fishingway,
      promotion,
      deposit,
      fishingReturns,
      fishingReleases,
      fishingTags,
      fishingTickets,
    } = item;
    return {
      baseInfo: {
        timerange,
        fishingway,
        promotion,
      },
      id,
      deposit,
      date: date.slice(0, 10),
      fishReturnData: fishingReturns,
      fishStockData: fishingReleases,
      tagFishData: fishingTags,
      feeData: fishingTickets,
    };
  },

  // 添加放钓
  async onAddSession() {
    const spotId = getApp().globalData.spotId;
    let nextData = formatDate(new Date());
    if (spotId) {
      wx.showLoading({
        title: "加载中...",
      });
      const res = await getSpotNextDate(spotId);
      console.log("========", res);
      if (res.error) {
        wx.showToast({
          title: "获取日期失败",
          icon: "none",
        });
        return;
      }
      wx.hideLoading();
      nextData = res.data.date;
    }
    wx.navigateTo({
      url: `/pages/goods/fishing-edit/fishing-edit?date=${nextData}`,
      events: {
        addSuccess: (data) => {
          console.log("接收到新增的数据:", data.newItem);
          const newSession = this.formatItem(data.newItem);
          this.setData({
            sessionList: this.data.sessionList.concat(newSession),
          });
        },
      },
    });
  },

  // 通用的字段保存事件
  onFieldSave(e) {
    const listIndex = e.currentTarget.dataset.index;
    const { field, detail } = e.detail;
    const { index, data, value } = detail;

    console.log(
      "===on fishing index===onFieldSave====",
      field,
      detail,
      listIndex
    );
    switch (field) {
      // case "baseInfo":
      //   this.setData({ [field]: data });
      //   break;
      // case "deposit":
      //   this.setData({ [field]: value });
      //   break;
      default: {
        const currentItem = this.data.sessionList[listIndex];
        const currentData = currentItem[field];
        // 数组类型
        if (index === -1) {
          // 新增
          currentData.push(data);
        } else {
          // 编辑
          currentData[index] = data;
        }
        this.setData({ [`sessionList[${listIndex}].${field}`]: currentData });
      }
    }
  },

  // 通用的字段删除事件
  onFieldDelete(e) {
    const { field, detail } = e.detail;
    const { index } = detail;
    const currentData = this.data[field];

    currentData.splice(index, 1);
    this.setData({ [field]: currentData });
  },
});
